let userList = [];
let chatList = [];

exports.mysocket = {
    user: {
        addUser(userInfo, ws) {
            let isHas = false;
            userList.map(item => {
                if (item.userInfo.name == userInfo.name) {
                    isHas = true;
                    return;
                }
            })
            if (!isHas) {
                userList.push({
                    userInfo: userInfo,
                    isLive: true,
                    wss: ws,
                    id: userList.length + 1
                })
            }
        }
    },
    socketMethrds: {
        /**
         * 获取用户列表
         * @returns 用户列表
         */
        getUserList() {
            let list = [];
            userList.map(item => {
                let user = { ...item };
                user.wss = null;
                list.push(user);
            });
            return list;
        }
    },
    msgMethords: {
        // type  1 单发   2群发   3 广播
        sendMsg(data) {
            let { type, recipient, msg } = data;
            switch (type) {
                case 1:
                    userList.forEach(item => {
                        if (item.userInfo.name == recipient) {
                            item.wss.on('open', function open(req) {
                                console.log('connected');
                            });
                            item.wss.on('close', function close() {
                                console.log('disconnected');
                                item.isLive = false;
                            });

                            chatList.push(data);
                            if (item.isLive) {
                                item.wss.send(JSON.stringify(chatList));
                            }
                        }
                    });
                    break;
                case 2:
                    userList.forEach(item => {
                        item.wss.send(JSON.stringify(chatList));
                    });
                    break;
            }
        }
    }
}